package com.googlecode.nls4j;

import java.util.Locale;
import java.util.ResourceBundle;

/**
 * A simple wrapper for {@linkplain ResourceBundle}.
 * 
 * @author Andrey Pavlenko
 */
public class ResourceBundleWrapper<K extends NlsKey<V>, V> implements
        NlsBundle<K, V> {
    private final ResourceBundle resourceBundle;

    /**
     * Wrap the specified {@code resourceBundle}.
     * 
     * @throws NullPointerException
     *             if {@code resourceBundle} is null.
     */
    public ResourceBundleWrapper(final ResourceBundle resourceBundle)
            throws NullPointerException {
        if (resourceBundle == null) {
            throw new NullPointerException();
        }
        this.resourceBundle = resourceBundle;
    }

    /**
     * Returns the resource bundle wrapped in this NlsBundle.
     */
    public ResourceBundle getResourceBundle() {
        return resourceBundle;
    }

    @Override
    @SuppressWarnings("unchecked")
    public V get(final K key) {
        final ResourceBundle b = getResourceBundle();
        final String name = key.getName();
        return b.containsKey(name) ? (V) b.getObject(name) : key
                .getDefaultValue(getLocale());
    }

    @Override
    public boolean contains(final K key) {
        return getResourceBundle().containsKey(key.getName());
    }

    @Override
    public Locale getLocale() {
        return getResourceBundle().getLocale();
    }
}
